#!/bin/bash
# Copyright (c) 2023, Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

(return 0 2>/dev/null) && IS_SOURCED=1 || IS_SOURCED=0

set -e


SCRIPT_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[[ -z "${BABBLESIM_INSTALL_DIR}" ]] && export BABBLESIM_INSTALL_DIR=~

echo ""
echo "Installing packages."

# In the AMI, the built in CMake is more recent than the apt one,
# and the apt one is too old to build the example, so we have to NOT
# install cmake if the current version is already up to date.

sudo apt-get update
sudo apt-get -y install \
bluez \
curl \
dbus \
expect \
gcc-multilib \
git \
python3 \
python3-pip \
python3-venv \

function satisfy_version {
    # $1 : version to check
    # $2 : minimum version accepted
    if [ "$(printf '%s\n' "$2" "$1" | sort -V | head -n1)" = "$2" ];
    then
        return 0
    else
        return 1
    fi
}

function get_cmake_version { cmake --version | head -n1 | cut -d ' ' -f 3; }

function install_cmake {
    sudo apt-get -y install cmake
    if ! satisfy_version $(get_cmake_version) $cmake_minimum;
    then
        echo "Could not install an up-to-date CMake. Installed version: $(cmake --version); minimum version required: $cmake_minimum"
        echo "Try a manual CMake install from kitware: https://askubuntu.com/questions/355565/how-do-i-install-the-latest-version-of-cmake-from-the-command-line"
        return 1
    fi
    return 0
}

cmake_minimum="3.20.0"
if cmake --version 2>&1 > /dev/null;
then
    if satisfy_version $(get_cmake_version) $cmake_minimum;
    then
        # The current cmake is good enough
        :
    else
        if ! install_cmake
        then
            if [ ${IS_SOURCED} -eq 0 ]
            then
                exit 1
            else
                return 1
            fi
        fi
    fi
else
    if ! install_cmake
    then
        if [ ${IS_SOURCED} -eq 0 ]
        then
            exit 1
        else
            return 1
        fi
    fi
fi


echo ""
echo "Building babblesim and related tools."

if [ ! -d "tools-for-babble-sim" ];
then
    git clone https://git.gitlab.arm.com/iot/open-iot-sdk/libraries/tools-for-babble-sim.git
fi

cd tools-for-babble-sim

if ! git config user.email > /dev/null
then
    git config --global user.email "ci@fake.com"
fi
if ! git config user.name > /dev/null
then
    git config --global user.name "ci"
fi
if ! git config color.ui > /dev/null
then
    git config --global color.ui true
fi

./build.sh


echo ""
echo "Installing babblesim and related tools."

# Install babblesim-tools, this will build the tools and copy them to a known location which will be added to the path.
# NOTE: A workaround is needed for the user to be able to call the binaries from anywhere.
# The binaries have hardcoded paths to libraries. Because of that for each binary in ${BABBLESIM_INSTALL_DIR}/babblesim-tools/bin
# we create a script file in ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts that will change the working dir and call the binary.
# Since ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts is the one that is added to the $PATH and the script names are identical to
# the tools binaries this will result in users being able to call the binaries from anywhere.
# babblesim works only on amd64

mkdir -p ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts
cp -r __build/bin ${BABBLESIM_INSTALL_DIR}/babblesim-tools/
cp -r __build/lib ${BABBLESIM_INSTALL_DIR}/babblesim-tools/
rm ${BABBLESIM_INSTALL_DIR}/babblesim-tools/bin/*.Tsymbols
for f in ${BABBLESIM_INSTALL_DIR}/babblesim-tools/bin/*
do
    printf "#\041/bin/bash\ncd ${BABBLESIM_INSTALL_DIR}/babblesim-tools/bin/ && ./\"\$(basename \$0)\" \"\$@\"" > ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/"$(basename $f)";
done
chmod +x ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/*

cd ..

# Adds it to path if it's not there already
[[ ! $PATH =~ "${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/" ]] && export PATH=${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/:${PATH}
if [ ${IS_SOURCED} -eq 0 ]
then
    echo ""
    echo "If ${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/ is not already in PATH, please export it : export PATH=${BABBLESIM_INSTALL_DIR}/babblesim-tools/scripts/:\${PATH}"
    echo "You may source this script instead next time to have PATH be set up automatically"
fi


echo ""
if [ -d "venv" ] && [ ! -L "venv" ]
then
    echo "Python virtual env already set up"
else
    echo "Installing python environment"
    pip install virtualenv
    python -m virtualenv venv
    source venv/bin/activate
    pip install -r ${SCRIPT_DIR}/requirements.txt
    deactivate
fi


# check if the bluetooth service is not running
if [[ -z "$(service bluetooth status | grep "not running")" ]];
then
    # check if the bluetooth kernel module is enabled
    if [[ -n "$(lsmod | grep "bluetooth")" ]];
    then
        sudo service bluetooth start
    else
        # check if the bluetooth kernel module is available
        if [[ -n "$(sudo modprobe bluetooth | grep "modprobe: FATAL: Module bluetooth not found")" ]];
        then
            sudo modprobe bluetooth
            sudo service bluetooth start
        else
            echo ""
            echo "Error : Bluetooth is not available in the current kernel. You might need to swap the kernel for one that do have bluetooth built in. See README.md for more instructions"
        fi
    fi
fi


echo ""
echo "Everything is setup. Once you've built the example you may run \"source venv/bin/activate\", then run \"${SCRIPT_DIR}/test.sh\""
